from flask import Blueprint, request, session, current_app
from models.comment import CommentModel
from models.user import UserModel
from datetime import datetime
from utils import restful
from hooks import login_auth
from exts import db


bp = Blueprint("comment", __name__, url_prefix="/comment")


# 1、根据博客获取评论-
@bp.route("/getPage/<int:blog_id>/<int:last_time>", methods=['GET'])
def get_comment_page_by_blog(blog_id, last_time):
    # 1、获取评论
    cs = []
    comments = get_comment_page(blog_id, last_time//1000)
    for c in comments:
        tmp = c.to_dict()
        tmp['user'] = c.user.username
        tmp['avatar'] = c.user.avatar
        cs.append(tmp)
    return restful.ok(data={'comments': cs})


# 2、添加评论
@bp.route('/create/<int:blog_id>', methods=['POST'])
@login_auth
def add_comment(blog_id):
    open_id = session.get('open_id')
    data = request.json
    content = data.get('content')
    res = {}
    if open_id:
        if content:
            dt = datetime.now()
            user = UserModel.query.get(open_id)
            comment = CommentModel(comment_user_id=open_id, comment_blog_id=blog_id, content=content, create_time=dt)
            db.session.add(comment)
            db.session.commit()
        else:
            return restful.params_error()
    else:
        return restful.unlogin_error()
    res['content'] = content
    res['create_time'] = dt.timestamp() * 1000
    print('评论添加时间', res['create_time'])  # 打印创建时间戳
    res['user'] = user.username
    res['avatar'] = user.avatar
    return restful.ok(message='添加成功', data={'comment':res})


# 3、删除评论
@bp.route('/delete/<int:comment_id>', methods=['DELETE'])
@login_auth
def delete_comment(comment_id):
    comment = CommentModel.query.get(comment_id)
    open_id = session.get('open_id')
    if comment and open_id:
        user = UserModel.query.get(open_id)
        # 是不是管理员
        if user.role == 1:
            db.session.delete(comment)
        # 判断是不是评论用户本身
        elif comment.comment_user_id == open_id:
            db.session.delete(comment)
        # 是不是博客作者
        elif comment.blog.author.open_id == open_id:
            db.session.delete(comment)
        else:
            return restful.permission_error()
    else:
        return restful.params_error()
    return restful.ok(message='删除成功')


def get_comment_page(blog_id, last_time):
    page_size = current_app.config['BLOG_PAGE_SIZE']
    # 1、处理时间信息
    last_time = datetime.fromtimestamp(last_time)
    # 2、获取该博客当页评论数据
    query = CommentModel.query\
        .filter(CommentModel.create_time < last_time, CommentModel.comment_blog_id == blog_id)\
        .order_by(CommentModel.create_time.desc())
    comments = query.limit(page_size).all()
    return comments
